  <template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="5" :offset="0">
            <el-form-item label="问题描述">
              <el-input v-model="searchForm.title" placeholder="问题描述" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>

      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="问题描述" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.title }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="文件类型" align="center">
            <template #default="{ row }">
              {{ transferFileType(row.fileType) }}
            </template>
          </el-table-column> -->

        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            {{ row.state == 0 ? "下架" : "上架" }}
          </template>
        </el-table-column>

        <el-table-column label="创建人" align="center">
          <template #default="{ row }">
            {{ row.createUsername }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
            <div v-else>

              <el-button v-if="scope.row.state == '0'" type="primary" size="small" text
                @click="handleEdit(scope.row)">修改</el-button>
              <el-button v-else type="primary" size="small" text disabled @click="handleEdit(scope.row)">修改</el-button>

              <el-popconfirm v-if="scope.row.state == '0'" title="是否要上架该资料？" confirmButtonText="确认"
                cancelButtonText="取消" @confirm="chageInfoLibState(scope.row.id, 1)">
                <template #reference>
                  <el-button type="primary" size="small" text>上架</el-button>
                </template>
              </el-popconfirm>

              <el-popconfirm v-if="scope.row.state == '1'" title="是否要下架该资料？" confirmButtonText="确认"
                cancelButtonText="取消" @confirm="chageInfoLibState(scope.row.id, 0)">
                <template #reference>
                  <el-button type="primary" size="small" text>下架</el-button>
                </template>
              </el-popconfirm>


              <el-popconfirm title="是否要删除该问答？" confirmButtonText="确认" cancelButtonText="取消"
                @confirm="handleDelete(scope.row.id)">
                <template #reference>
                  <el-button v-if="scope.row.state == '0'" text type="primary" size="small">删除</el-button>
                  <el-button v-else text type="primary" size="small" disabled>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
          :page-size="limit" @current-change="initTableData" />
      </div>

      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit" @isClosed="isClosed" size="60%">

        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">

          <el-form-item label="问题描述" prop="title">
            <el-input v-model="form.title" placeholder="问题描述"></el-input>
          </el-form-item>

          <el-form-item label="问题答疑" prop="content">
            <Editor v-if="showEditor" :contentHtml="form.content" ref="editorRef" />
          </el-form-item>

        </el-form>
      </FormDrawer>

    </el-card>
  </template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue"
import Editor from "~/components/editor.vue";
import { toast, toastWarn } from "~/composables/util"
import { dateFormatter } from '~/utils/common.js'
import { addInfoLibrary, getInfoLibraryList, editInfoLibrary, deleteInfoLibrary, updateInfoLibState } from "~/api/supply"

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

// 查询条件
const searchForm = reactive({
  title: "",
  //资料类型（0：操作手册 1：常见问答）
  type: "1",
  page: currentPage.value,
  size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
  searchForm.title = ""
  initTableData(1)
}

const tableData = ref([])
const loading = ref(false)
const editorRef = ref(null)
const showEditor = ref(false)

// 生命周期函数
onMounted(() => {
  //初始化列表数据
  initTableData()
})


// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  getInfoLibraryList(searchForm)
    .then(res => {
      if (res) {
        tableData.value = res.records
        total.value = res.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 删除
const handleDelete = (id) => {
  loading.value = true
  deleteInfoLibrary(id).then(res => {
    toast("删除成功")
    initTableData()
  })
    .finally(() => {
      loading.value = false
    })
}

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
  title: null,
  content: null,
  fileList: []
})
//执行表单校验
const rules = {
  title: [
    { required: true, message: '问题描述不能为空', trigger: 'change' }
  ],
  content: [
    { required: true, message: '问题答疑不能为空', trigger: 'change' }
  ]
}

//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")

//提交表单
const handleSubmit = () => {

  //获取组件值赋值给form.content
  form.content = editorRef.value.valueHtml

  //表单校验
  formRef.value.validate((valid) => {
    if (!valid) return
    let fun = null
    //新增
    if (editId.value == 0) {
      let paramIo = new FormData()// FormData 对象
      paramIo.append('title', form.title)
      paramIo.append('content', form.content)
      //资料类型（0：操作手册 1：常见问答）
      paramIo.append('type', '1')
      //添加资料库
      //loading
      formDrawerRef.value.showLoading()
      fun = addInfoLibrary(paramIo)
    }
    else {
      //loading
      formDrawerRef.value.showLoading()
      //修改
      fun = editInfoLibrary(editId.value, form)
    }
    fun.then(res => {
      toast(drawerTitle.value + "成功")
      //修改刷新当前页，新增刷新第一页
      initTableData(editId.value ? false : 1)
      formDrawerRef.value.close()
      showEditor.value = false
    })
      .finally(() => {
        //close loading
        formDrawerRef.value.hideLoading()
      })
  })
}

//关闭
const isClosed = () => {
  //console.log("isClosed")
  //editorRef.value.destroyEditor()
  showEditor.value = false
}

// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}

// 新增按钮点击事件
const handleCreate = () => {
  //修改标记置为0
  editId.value = 0
  resetForm({
    title: null,
    content: null,
    filelist: []
  })
  //打开弹窗
  formDrawerRef.value.open()
  showEditor.value = true
}

// 编辑
const handleEdit = (row) => {
  editId.value = row.id
  resetForm(row)
  formDrawerRef.value.open()
  showEditor.value = true
}

// 上架|下架资料
const chageInfoLibState = (id, status) => {
  loading.value = true
  updateInfoLibState(id, status).then(res => {
    if (status == "1") {
      toast("上架成功")
    } else {
      toast("下架成功")
    }
    initTableData()
  })
    .finally(() => {
      loading.value = false
    })
}
</script>